<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->
<template>
    <div class="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100 p-8">
        <div class="mx-auto max-w-7xl">
            <!-- 系统标题 -->
            <div class="mb-8 flex items-center" style="justify-content: center;">
                <h1
                    class="text-3xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-blue-600 to-indigo-600">
                    JBolt AI智能客户跟进管理</h1>
            </div>
        </div>
        <!-- 录入区域 -->
        <div class="mb-8">
            <div class="grid grid-cols-2 gap-6 mb-8">
                <div
                    class="rounded-lg bg-white p-6 shadow-xl ring-1 ring-black ring-opacity-5 backdrop-blur-lg relative">
                    <div class="mb-6">
                        <h1 class="text-2xl font-bold text-gray-800">客户信息录入</h1>
                        <div class="mt-6 space-y-4">
                            <div>
								<textarea rows="6" v-model="inputData"
                                          class="w-full rounded-lg border-gray-300 px-4 py-2 text-sm focus:border-blue-500 focus:ring-blue-500"
                                          placeholder="请输入与客户沟通的内容，AI 将自动分析并生成跟进记录..."></textarea>
                            </div>
                            <div class="flex justify-end space-x-4">
                                <button @click="handleGenerateSampleData"
                                        class="!rounded-button flex items-center whitespace-nowrap bg-gradient-to-r from-green-600 to-teal-600 px-4 py-2 text-white hover:from-green-700 hover:to-teal-700 transform transition-transform duration-200 hover:scale-105 shadow-md">
                                    <i class="fa-solid fa-database mr-2"></i>生成案例数据
                                </button>
                                <button @click="handleGenerateRecord"
                                        class="!rounded-button flex items-center whitespace-nowrap bg-gradient-to-r from-blue-600 to-indigo-600 px-4 py-2 text-white hover:from-blue-700 hover:to-indigo-700 transform transition-transform duration-200 hover:scale-105 shadow-md">
                                    <i class="fa-solid fa-magic mr-2"></i>智能生成跟进记录
                                </button>
                            </div>
                        </div>
                    </div>
                    <!-- AI处理遮罩层 -->
                    <div v-if="isProcessing"
                         class="absolute inset-0 bg-white/80 backdrop-blur-sm flex items-center justify-center transition-opacity duration-300">
                        <div class="text-center">
                            <div
                                class="inline-block animate-spin rounded-full h-12 w-12 border-4 border-blue-600 border-t-transparent mb-4">
                            </div>
                            <p class="text-lg text-gray-700">AI 智能分析处理中...</p>
                        </div>
                    </div>
                </div>
                <div class="rounded-lg bg-white p-6 shadow-xl ring-1 ring-black ring-opacity-5 backdrop-blur-lg">
                    <div class="mb-6 flex items-center justify-between">
                        <h1 class="text-2xl font-bold text-gray-800">客户跟进记录</h1>
                        <button
                            class="!rounded-button flex items-center whitespace-nowrap bg-gradient-to-r from-blue-600 to-indigo-600 px-4 py-2 text-white hover:from-blue-700 hover:to-indigo-700 transform transition-transform duration-200 hover:scale-105 shadow-md"
                            @click="handleSubmit">
                            <i class="fa-solid fa-plus mr-2"></i>提交记录
                        </button>
                    </div>
                    <div>
                        <n-form ref="formRef" :model="formData" :rules="rules"
                                style="display: flex;width: 100%;justify-content: space-between;flex-direction: column;">
                            <div style="display: flex;">
                                <n-form-item label="客户名称" path="customerName" style="width: 33%;">
                                    <input v-model="formData.customerName" type="text"
                                           class="w-full rounded-lg border-gray-300 px-4 py-2 text-sm focus:border-blue-500 focus:ring-blue-500 transition-shadow duration-200 hover:shadow-sm"
                                           placeholder="请输入客户名称"/>
                                </n-form-item>
                                <n-form-item label="跟进类型" path="type" style="width: 31%;margin-right: 3%;">
                                    <jb-select v-model:value="formData.type"
                                               url="/customerRecord/getCustomerRecordTypeList" placeholder="请选择类型"
                                               label-field="text" value-field="value">
                                    </jb-select>
                                </n-form-item>
                                <n-form-item label="重要程度" path="type" style="width: 33%;">
                                    <jb-radio-group v-model:value="formData.level"
                                                    url="/customerRecord/getCustomerRecordLevelList">

                                    </jb-radio-group>
                                </n-form-item>
                            </div>
                            <div>
                                <n-form-item label="跟进内容" path="content">
									<textarea v-model="formData.content" rows="4"
                                              class="w-full rounded-lg border-gray-300 px-4 py-2 text-sm focus:border-blue-500 focus:ring-blue-500"
                                              placeholder="请输入跟进内容"></textarea>
                                </n-form-item>
                            </div>

                        </n-form>

                    </div>
                </div>
            </div>
            <!-- 历史记录区域 -->
            <div class="rounded-lg bg-white p-6 shadow-xl ring-1 ring-black ring-opacity-5 backdrop-blur-lg">
                <div class="mb-6 flex flex-wrap items-center justify-between gap-4">
                    <div class="flex flex-1 items-center space-x-4">
                        <div class="relative flex-1">
                            <input v-model="searchKeyword" type="text"
                                   class="w-full rounded-lg border-gray-300 pl-10 pr-4 py-2 text-sm focus:border-blue-500 focus:ring-blue-500"
                                   placeholder="搜索客户名称、跟进内容"/>
                            <i class="fa-solid fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
                        </div>
                    </div>
                </div>

                <!-- 记录列表 -->
                <div class="overflow-x-auto" v-if="show">
                    <table
                        class="min-w-full divide-y divide-gray-200 shadow-sm transition-all duration-300 hover:shadow-lg">
                        <thead>
                        <tr>
                            <th v-for="header in tableHeaders" :key="header.key"
                                class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                {{ header.label }}
                            </th>
                        </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                        <tr v-for="record in records" :key="record.id"
                            :class="{'bg-red-50': record.level === 'exigency', 'bg-yellow-50': record.level === 'importance'}"
                            class="transition-all duration-300 ease-in-out hover:shadow-md hover:bg-gray-50 hover:scale-[1.005] hover:translate-x-1">
                            <td
                                class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 transition-colors duration-300 hover:text-blue-600">
                                {{ record.createTime }}
                            </td>
                            <td
                                class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 transition-colors duration-300 hover:text-blue-600">
                                {{ record.customerName }}
                            </td>
                            <td
                                class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 transition-colors duration-300 hover:text-blue-600">
                                {{ record.typeName }}
                            </td>
                            <td
                                class="px-6 py-4 text-sm text-gray-900 transition-colors duration-300 hover:text-blue-600">
                                <div class="max-w-md overflow-hidden text-ellipsis">{{ record.content }}</div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm">
                                <span :class="getPriorityClass(record.level)">{{ record.levelName }}</span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">admin</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">

                                <button
                                    class="!rounded-button text-red-600 hover:text-red-800 transition-transform duration-300 hover:scale-110"
                                    @click="deleteRecord(record.id)">
                                    <i class="fa-solid fa-trash"></i>
                                </button>
                            </td>
                        </tr>
                        </tbody>
                    </table>
                </div>
                <div class="rounded-lg bg-white p-6 shadow-xl ring-1 ring-black ring-opacity-5 backdrop-blur-lg" v-else
                     style="height: 400px;line-height: 400px;">
                    <h1 class="no-follow-up-title">暂无跟进记录</h1>
                </div>

            </div>

        </div>
    </div>
</template>
<script  setup>
import {onMounted, reactive, ref, watch} from 'vue'
import {JBoltApi} from '@/service/request'
import {useMessage} from 'naive-ui'
import {useWebSocketStore} from "@/stores/websocket.js";
import {storeToRefs} from "pinia";
import AiChat from '@/components/_builtin/jb-ai-chat/index.js'


const message = useMessage()
const inputData = ref("")
const webSocketStore = storeToRefs(useWebSocketStore())
const currentSession = ref({})	//默认当前的session对象
const chatContainer = ref(null)
const chatInstance = ref(null)
const formRef = ref(null)
const show = ref(false);
const isProcessing = ref(false);
const searchKeyword = ref('');
const records = ref([]);
const formData = ref({
    customerName: '',
    type: '',
    level: 'normal',
    content: ''
});
const rules = {
    customerName: {
        required: true,
        message: '请输入客户名称',
        pattern: /\S/, // 至少有一个非空白字符
        trigger: 'change'
    },
    type: {
        required: true,
        message: '请选择跟进类型',
        trigger: 'change'
    },
    level: {
        required: true,
        message: '请选择重要程度',
        trigger: 'change'
    },
    content: {
        required: true,
        pattern: /\S/, // 至少有一个非空白字符
        message: '请输入跟进内容',
        trigger: 'change'
    }
}


//填充数据
const handleGenerateSampleData = () => {
    inputData.value = "与广州未来科技股份有限公司的技术总监王工进行了深入交流。对方对我们的智能工厂解决方案表现出极大兴趣，特别关注我们在生产线优化和预测性维护方面的能力。王工提到他们公司正在寻求提高生产效率和降低成本的解决方案，我们的产品恰好能满足这些需求。他希望能够安排一次详细的技术方案演示和成本效益分析。我们约定下周三下午2点进行线上会议，届时需要准备具体的技术参数和案例分析。整体来说，这是一个很有潜力的客户，需要积极跟进。";
};

watch(() => searchKeyword.value, () => {
    getList();
})

watch(() => webSocketStore.ws.value, () => {
    console.debug("websock重连")
    if (chatInstance.value) {
        chatInstance.value.updateWebSocket(webSocketStore.ws.value)
    }
})

watch(() => chatContainer.value, (newV) => {
    if (newV && !chatInstance.value) {
        loadChatInstance()
    }
})
watch(() => useWebSocketStore().ws.value, (newV) => {

    if (chatContainer.value && newV) {
        chatInstance.value.updateWebSocket(useWebSocketStore().ws.value)
    }
})


const tableHeaders = [
    {key: 'createTime', label: '跟进时间'},
    {key: 'customerName', label: '客户名称'},
    {key: 'type', label: '跟进类型'},
    {key: 'content', label: '跟进内容'},
    {key: 'level', label: '重要程度'},
    {key: 'operator', label: '操作人'},
    {key: 'actions', label: '操作'}
];


const getPriorityClass = (priority) => {
    switch (priority) {
        case 'exigency':
            return 'px-2 py-1 text-xs font-medium rounded-full bg-red-100 text-red-800';
        case 'importance':
            return 'px-2 py-1 text-xs font-medium rounded-full bg-yellow-100 text-yellow-800';
        case 'normal':
            return 'px-2 py-1 text-xs font-medium rounded-full bg-gray-100 text-gray-800';
    }
};
//智能生成跟进记录
const handleGenerateRecord = () => {
    formData.value = {
        customerName: '',
        type: '',
        level: 'normal',
        content: ''
    }
    isProcessing.value = true;
    chatInstance.value.sendMessage({
        action: 'request',
        data: {
            role: "user",
            content: {"text": inputData.value}
        }
    });
};

function deleteRecord(id) {
    JBoltApi.get("/customerRecord/delete/" + id).then((res) => {
        getList();
        message.success('移除成功');
    });
};


const handleSubmit = async () => {
    await formRef.value?.validate();
    add();
};

function add() {
    console.log(JSON.stringify(formData.value))
    JBoltApi.post("/customerRecord/add", formData.value)
        .then((res) => {
            // 重置表单
            getList();
            formData.value = {
                customerName: '',
                type: '',
                level: 'normal',
                content: ''
            };
        });
}

function getList() {
    JBoltApi.get("/customerRecord/list", {
        keywords: searchKeyword.value
    }).then((res) => {
        let list = res.result.data;
        if (list == null || list.length == 0) {
            show.value = false;
        } else {
            show.value = true;
            records.value = list;
        }

    });
}

//添加会话
function addSession() {
    JBoltApi.post('/aiAppSession/add', {
        name: '新的 智能客户跟进系统 会话',
        appId: import.meta.env.VITE_APP_ID,

    }).then((res) => {
        currentSession.value = res.result.data;
        loadChatInstance();
    });
}
const allMessage = ref('');
function loadChatInstance() {
    //初始化aichat
    chatInstance.value = new AiChat(chatContainer.value, {
        websocketInstance: webSocketStore.ws.value,
        app: import.meta.env.VITE_APP_ID,
        sessionId: currentSession.value.id,
        global: null,
        onMsgSend: (msg) => {
        },
        onMsgReceive: (data) => {

            if (data.action == 'response') {
                allMessage.value=allMessage.value+data.data.content.text
            }
            if (data.action == 'over') {
                isProcessing.value = false;
                try {
                    let json = JSON.parse(allMessage.value);
                    formData.value = json;
                } catch (error) {
                    message.error("对不起,无法识别您录入的信息,请重新录入~")

                }
            }
        }
    })
}

onMounted(() => {
    getList();
    addSession();

});
</script>
<style scoped>
.custom-input::-webkit-outer-spin-button,
.custom-input::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
}

input,
textarea,
button {
    transition: all 0.2s ease-in-out;
}

input:focus,
textarea:focus {
    box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.no-follow-up-title {
    height: 100%;
    /* display: flex; */
    font-size: 28px;
    font-weight: 600;
    color: #333;
    text-align: center;
}
</style>